package sk.tuke.client.view;

import sk.tuke.client.ApplicationClickHandler;
import sk.tuke.client.interfaces.LayoutFactory;

import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.RestDataSource;
import com.smartgwt.client.types.DSDataFormat;
import com.smartgwt.client.types.FieldType;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.HTMLPane;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.form.ValuesManager;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

public class PatientProfileView extends VLayout {
	
	private Integer patientsNumber;
	final ValuesManager patientValuesManager = new ValuesManager();
	final ValuesManager insuranceValuesManager = new ValuesManager();
	HTMLPane patientHTMLPane = new HTMLPane();
	HTMLPane insuranceHTMLPane = new HTMLPane();
	
	public PatientProfileView(Integer patientsNumber) {
		super();
		this.patientsNumber=patientsNumber;
		initLayout();
	}

	private void initLayout(){
		
		RestDataSource patientDatasource = new RestDataSource();  
        patientDatasource.setDataURL("http://localhost:8080/healthCard/usermanagement/getpatients");  
        patientDatasource.setRecordXPath("GetPatientsOutput/patients");  
        patientDatasource.setCallbackParam("GetPatientsOutput");
        patientDatasource.setDataFormat(DSDataFormat.JSON);
        
        RestDataSource insuranceDatasource = new RestDataSource();  
        insuranceDatasource.setDataURL("http://localhost:8080/healthCard/businessmanagement/getinsurance");  
        insuranceDatasource.setRecordXPath("GetInsuranceOutput/insurance");  
        insuranceDatasource.setCallbackParam("GetInsuranceOutput");
        insuranceDatasource.setDataFormat(DSDataFormat.JSON);
        
        RestDataSource medicalRecordsDatasource = new RestDataSource();  
        medicalRecordsDatasource.setDataURL("http://localhost:8080/healthCard/healthcardmanagement/gethealthcard");  
        medicalRecordsDatasource.setRecordXPath("GetHealthCardOutput/healthCard/medicalRecords");  
        medicalRecordsDatasource.setCallbackParam("GetHealthCardOutput");
        medicalRecordsDatasource.setDataFormat(DSDataFormat.JSON);
        
        DataSourceField number = new DataSourceField("number", FieldType.INTEGER, "Number");  
        DataSourceField date = new DataSourceField("date", FieldType.DATE, "Date");  
        DataSourceField diseases = new DataSourceField("diseases", FieldType.TEXT, "Drug");
        DataSourceField symptoms = new DataSourceField("symptoms", FieldType.TEXT, "Drug");
        DataSourceField drugs = new DataSourceField("drugs", FieldType.TEXT, "Drug");
        DataSourceField status = new DataSourceField("status", FieldType.TEXT, "Status");
        medicalRecordsDatasource.setFields(number, date, diseases, symptoms, drugs, status);  
        
        patientValuesManager.setDataSource(patientDatasource);
        insuranceValuesManager.setDataSource(insuranceDatasource);
        
        Criteria criteria = new Criteria("number", String.valueOf(patientsNumber));
        patientValuesManager.fetchData(criteria, new DSCallback() {
			public void execute(DSResponse response, Object rawData, DSRequest request) {
				
				String html = "<span style='font-size: 13px'><b>" +
		    			patientValuesManager.getValueAsString("firstname") + " " +
		    			patientValuesManager.getValueAsString("middlename") + " " +
		    			patientValuesManager.getValueAsString("lastname") + "</b><br/>" +
						"</span><span style='font-size: 12px'>"+
		    			"<b>Personal ID:</b> " + patientValuesManager.getValueAsString("number") + "<br/>" +
		    			"<b>Phone:</b> " + patientValuesManager.getValueAsString("phone/phoneNumber") + "<br/>"+
		    			"<b>E-Mail:</b> " + patientValuesManager.getValueAsString("email") + "</span><br/><br/>" +
						"<span style='font-size: 13px'>" + patientValuesManager.getValueAsString("address/street") + " " +
						patientValuesManager.getValueAsString("address/streetNum") + "<br/>" +
						patientValuesManager.getValueAsString("address/zip") + " " +
						patientValuesManager.getValueAsString("address/city") + "<br/>" +
						patientValuesManager.getValueAsString("address/country") + "</span>";
		    	patientHTMLPane.setContents(html);
		    	patientHTMLPane.redraw();

		        Criteria criteria = new Criteria("number", patientValuesManager.getValueAsString("insuranceNumber"));
		        insuranceValuesManager.fetchData(criteria, new DSCallback() {
					public void execute(DSResponse response, Object rawData, DSRequest request) {
						String html = "<span style='font-size: 12px'><u>Insurance:</u><br/><b>" +
				    			insuranceValuesManager.getValue("name").toString() + "</b><br/>" +
				    			insuranceValuesManager.getValue("street").toString() + " " +
				    			insuranceValuesManager.getValue("streetNum").toString() + "<br/>" +
				    			insuranceValuesManager.getValue("zip").toString() + " " +
				    			insuranceValuesManager.getValue("city").toString() + "<br/>" +
				    			insuranceValuesManager.getValue("state").toString() +
				    			"<br/><br/><b>Insurance number:</b> " + insuranceValuesManager.getValue("number").toString() + "<br/>" +
				    			"<b>Contact person:</b> " + insuranceValuesManager.getValue("contactPerson").toString() + "<br/>" +
				    			"<b>Phone:</b> " + insuranceValuesManager.getValue("phone").toString() + "<br/>" +
				    			"<b>E-Mail:</b> " + insuranceValuesManager.getValue("email").toString() + "</span>";
						insuranceHTMLPane.setContents(html);
						insuranceHTMLPane.redraw();
					}
				});
		        
		        
		        healthCardGrid.fetchData(new Criteria("number", patientValuesManager.getValueAsString("healthCardNumber")));
			}
        });
        
		patientHTMLPane.setOverflow(Overflow.VISIBLE);
		patientHTMLPane.setWidth(350);
		patientHTMLPane.setContents("No patients data loaded");
		
		insuranceHTMLPane.setOverflow(Overflow.VISIBLE);
		insuranceHTMLPane.setContents("No patients data loaded");
		
		HLayout personalInfoLayout = new HLayout(10);
		personalInfoLayout.setBorder("1px solid lightgray");
		personalInfoLayout.setWidth100();
		personalInfoLayout.setAutoHeight();
		personalInfoLayout.setPadding(10);
		personalInfoLayout.addMember(patientHTMLPane);
		personalInfoLayout.addMember(insuranceHTMLPane);
		
		Button healthCardButton = new Button("View health card");
		healthCardButton.addClickHandler(new ApplicationClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				HealthCardView.Factory factory = new HealthCardView.Factory();
				Canvas view = factory.create(Integer.parseInt(patientValuesManager.getValueAsString("healthCardNumber")));
				southLayout.setMembers(view, westLayout);
			}
			
		});
		
		VLayout tableLayout = new VLayout(2);
		tableLayout.setPadding(40);
		Label label = new Label("Last medical records: (not implemented) ");
		label.setHeight(15);
		tableLayout.addMember(label);	
        
        healthCardGrid.setShowRecordComponents(true);          
        healthCardGrid.setShowRecordComponentsByCell(true);   
        healthCardGrid.setShowFilterEditor(true);  
        healthCardGrid.setFilterOnKeypress(true);
        healthCardGrid.setHeight(200);
        healthCardGrid.setDataSource(medicalRecordsDatasource);    
        healthCardGrid.setShowAllRecords(true);
        
        ListGridField numberField = new ListGridField("number", 60);
        numberField.setCanFilter(false);
        ListGridField diseaseField = new ListGridField("diseases", "Disease");
        diseaseField.setDataPath("/diagnose/disease/name");
        ListGridField symptomsField = new ListGridField("symptoms");
        symptomsField.setDataPath("/diagnose/symptoms/name");
        ListGridField drugsField = new ListGridField("drug", "Drugs");
        drugsField.setDataPath("/diagnose/drugs/name");
        ListGridField dateField = new ListGridField("date", "Date");
        ListGridField statusField = new ListGridField("status", "Status");
        ListGridField menuField = new ListGridField("menuField", "Menu", 60);
        menuField.setCanFilter(false);
        healthCardGrid.setFields(numberField, diseaseField, symptomsField, drugsField, dateField, statusField, menuField);
        tableLayout.addMember(healthCardGrid);
        
		// add members to the Accounts View layout container
		VLayout a = new VLayout();
		a.addMember(personalInfoLayout);
		a.addMember(healthCardButton);
		a.addMember(tableLayout);
		a.setMargin(30);
		a.setWidth100();
		this.addMember(a);
		this.setOverflow(Overflow.AUTO);
		
		// initialise the Accounts View layout container
		this.addStyleName("crm-ContextArea");
		this.setWidth("*");

	}
	
	final ListGrid healthCardGrid = new ListGrid() {  
        @Override  
        protected Canvas createRecordComponent(final ListGridRecord record, Integer colNum) {  

            String fieldName = this.getFieldName(colNum);  

            if (fieldName.equals("menuField")) {  
                HLayout recordCanvas = new HLayout(3);  
                recordCanvas.setHeight(22);    
             
                ImgButton openImg = new ImgButton();
                openImg.setShowDown(false);  
                openImg.setShowRollOver(false);   
                openImg.setSrc("open.png");  
                openImg.setPrompt("Open Record");  
                openImg.setHeight(16);  
                openImg.setWidth(16);
                openImg.addClickHandler(new ApplicationClickHandler(){
        			@Override
        			public void onClick(ClickEvent event) {
        				MedicalRecordView.Factory factory = new MedicalRecordView.Factory();
        				Canvas view = factory.create(record.getAttributeAsInt("number"));
        				southLayout.setMembers(view, westLayout);
        			}
                });

                ImgButton editImg = new ImgButton();  
                editImg.setShowDown(false);  
                editImg.setShowRollOver(false);  
                editImg.setSrc("edit.png");  
                editImg.setPrompt("Edit Record");  
                editImg.setHeight(16);  
                editImg.setWidth(16);  
                editImg.addClickHandler(new ApplicationClickHandler(){
        			@Override
        			public void onClick(ClickEvent event) {
        				SC.say("Not implemented");
        			}
                });
                
                recordCanvas.addMember(openImg);  
                recordCanvas.addMember(editImg);
                return recordCanvas;  
            } else {  
                return null;  
            }  

        }  
    };
	

	public static class Factory implements LayoutFactory {

		public Canvas create() {
			return new PatientProfileView(null);
		}
		
		public Canvas create(Integer patientsNumber) {
			return new PatientProfileView(patientsNumber);
		}
		
		
	}
}
